<?php

namespace app\admin\controller\benefit;

use DateTime;
use think\App;
use app\Request;
use think\facade\Db;
use think\facade\Log;
use think\facade\Cache;
use think\response\Json;
use think\exception\ValidateException;
use think\db\exception\DbException;

use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use PhpOffice\PhpSpreadsheet\Reader\Exception;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;

use app\admin\service\UploadService;
use app\common\controller\AdminController;
use app\admin\service\annotation\ControllerAnnotation;
use app\admin\service\annotation\NodeAnnotation;

use app\admin\model\OtherCyl;
use app\admin\model\OtherZcf;
use app\admin\model\OtherLwf;
use app\admin\model\BenefitLwf;
use app\admin\model\BenefitZcf;
use app\admin\model\BenefitRcl;
use app\admin\model\BenefitLog;
use app\admin\model\SystemUploadfile;
use app\admin\model\BenefitWellNumber;

#[ControllerAnnotation(title: '效益管理')]
class Calculate extends AdminController
{

    private array $notes;

    #[NodeAnnotation(ignore: ['add', 'edit', 'delete', 'modify', 'recycle'])]
    protected array $ignoreNode;

    //参数验证
    private array $rule = [
        'start'  => 'require',
        'end'   => 'require'
    ];
    private array $message = [
        'start.require'   => '请选择开始日期',
        'end.require'   => '请选择结束日期'
    ];

    protected array $sort = [
        'file'   => 'desc',
        'calculate_days' => 'desc',
    ];

    public function __construct(App $app)
    {
        parent::__construct($app);
        self::$model = new \app\admin\model\BenefitWellNumber();
        $notes = self::$model::$notes;

        $this->notes = $notes;
        $this->assign(compact('notes'));
    }

    #[NodeAnnotation(title: '列表', auth: true)]
    public function index(Request $request): Json|string
    {
        if ($request->isAjax()) {
            list($page, $limit, $where) = $this->buildTableParams();
            $count = self::$model::where($where)->count();
            $list  = self::$model::where($where)
                ->where('user', session('admin.id'))
                ->page($page, $limit)
                ->order($this->sort)
                ->select()->toArray();
            $data  = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }


    #[NodeAnnotation(title: '详情', auth: true)]
    public function detail(Request $request, $id = 0): string
    {
        $row = BenefitWellNumber::find($id);
        empty($row) && $this->error('数据不存在');
        $extraction_rule = "";
        $file = SystemUploadfile::where('new_name', $row->file)->find();
        if (!empty($file)) {
            $extraction_rule = $file->extraction_rules;
        }
        $log = BenefitLog::where(array('well_number' => $row->well_number, 'file' => $row->file, 'user' => session('admin.id')))->select()->toArray();
        $this->assign('extraction_rule', $extraction_rule);
        $this->assign('row', $row);
        $this->assign('log', $log);
        return $this->fetch();
    }

    #[NodeAnnotation(title: '计算效益', auth: true)]
    public function calculate(Request $request)
    {
        $key = uploadkey();
        $file = Cache::get($key);
        //$file = '1761186528orD1';
        if (empty($file)) {
            $this->error('请先上传文件后再计算');
        }
        $file_model = SystemUploadfile::where(array('new_name' => $file))->find();
        if (empty($file_model)) {
            $this->error('未查询到文件信息，请重新上传文件');
        }
        $well_number_array = BenefitWellNumber::where(array('file' => $file))->select();
        //$well_number_array = [BenefitWellNumber::where(array('file' => $file))->find()];

        if ($request->isPost()) {
            $time = time();
            $post = request()->post();
            $end_date = $post['end_date'];
            if (empty($end_date)) {
                $end_date = date('Y-m-d');
            }
            foreach ($well_number_array as $model) {
                $model_well_number = $model->well_number;
                $model->before_capacity = $this->measures_before_cl($model);
                $model->after_capacity = $this->measures_after_cl($model);
                $model->capacity_difference = formatNumber($model->after_capacity - $model->before_capacity);
                BenefitRcl::where(array('JH'=>$model_well_number,'file'=>$model->file))->delete();
                if (!empty($model->measures_after_date) && ($model->capacity_difference >= 0)) {
                    $model->measures_after_end_date    = $end_date;
                    $model->calculate_days = $this->dateinterval($model->measures_after_end_date, $model->measures_after_date);
                    $model->calculate_days = $model->calculate_days > 1 ? $model->calculate_days : 1;
                    $model->difference_benefit = formatNumber(($model->capacity_difference * benefitConfig('oil_price')) * $model->calculate_days);
                }
                $where = array(
                    'F_KGRQ' => $model->start_date,
                    'F_WGRQ' => $model->end_date,
                    'F_GCMC' => $model_well_number,
                    'FILE' => $model->file,
                );
                $key = 'F_DMBTR';
                $where['TYPE'] = 0;
                $model->normal_labor_cost = formatNumber(BenefitLwf::where($where)->sum($key));

                $where['TYPE'] = 1;
                $model->self_labor_cost = formatNumber(BenefitLwf::where($where)->sum($key));

                $where['TYPE'] = 2;
                $model->other_labor_cost = formatNumber(BenefitLwf::where($where)->sum($key));

                $jcf = BenefitZcf::where(array('F_JH' => $model_well_number, 'FILE' => $model->file))
                    ->whereBetween('F_FLSJ', [$model->start_date, $model->end_date])->sum('F_JE');
                $model->material_cost = formatNumber($jcf);

                $model->benefit = $model->difference_benefit - $model->normal_labor_cost - $model->material_cost;
                $model->result = $model->benefit > 0 ? 1 : 0;
                $model->save();
            }
            $this->success("计算已完成");
        }
        $info = array(
            'well_number_count' => count($well_number_array),
            'date_range' => $file_model->date_range,
            'file' => $file
        );
        $this->assign('info', $info);
        return $this->fetch();
    }

    #[NodeAnnotation(title: '上传', auth: true)]
    public function upload(Request $request)
    {
        if ($request->isPost()) {
            $start_time = time();
            //验证文件
            $files = request()->file();
            if (empty($files)) {
                $this->error("Excel文件不能为空");
                return;
            }
            $uploadConfig = sysConfig('upload');
            $rule = [
                'file|文件' => "require|file|fileExt:{$uploadConfig['upload_allow_ext']}|fileSize:{$uploadConfig['upload_allow_size']}",
            ];
            $message = [
                'file.fileExt' => '请上传正确的Excel文件'
            ];
            $this->validate($files, $rule, $message); //校验文件类型

            //验证参数
            $post = request()->post();
            $this->validate($post, $this->rule, $this->message);
            //上传文件
            $upload = $this->upload_file($request);
            $code = $upload['code'] ?? 0;
            if ($code == 1) {
                //文件上传成功，下面开始提取数据
                $upload_data = $upload['data'];
                $publicPath = app()->getRootPath() . 'public' . DIRECTORY_SEPARATOR;
                // 拼接具体文件路径（例如读取public下的test.txt）
                $file_path = $publicPath . $upload_data['url'];
                // // 检查文件是否存在
                if (!file_exists($file_path)) {
                    $upload['code'] = 0;
                    $upload['msg'] = "Excel不存在，请重新上传";
                    return json($upload);
                }
                $new_name = $upload['data']['name'];
                $range = $post['start'] . '/' . $post['end'];
                $data = $this->readExcelData($file_path, $new_name, $range);
                $msg = '';
                if (count($data) > 0) {
                    $model = new BenefitWellNumber();
                    //提取出的井号保存到本地数据库
                    $this->save_data($data, $model);
                    //查询各个井号的费用
                    $res = $this->query_cost($new_name);
                    if ($res == true) {
                        $code = 1;
                        $msg = "文件上传成功";
                        $time = 1800;
                        $key = uploadkey();
                        Cache::set($key, $new_name, $time);
                    } else {
                        $code = 0;
                        $msg = "费用数据查询失败，请重新上传";
                        $this->deletefile($new_name);
                    }
                } else {
                    $code = 0;
                    $msg = "暂未提取到满足条件的记录";
                    $this->deletefile($new_name);
                }
                $upload['code'] = $code;
                $upload['msg'] = $msg;
                unset($upload['data']);
                $time_interval = time() - $start_time;
                Log::info("累积耗时{$time_interval}s");
                return json($upload);
            } else {
                $upload['code'] = 0;
                $upload['msg'] = "文件上传失败";
                return json($upload);
            }
        }
        return $this->fetch('upload');
    }

    //措施前产量
    public function measures_before_cl($model)
    {
        $measures_before_times  = benefitConfig('measures_before_times');
        $measures_before_interval  = benefitConfig('measures_before_interval');
        $measures_before_type  = intval(benefitConfig('measures_before_type')) == 0 ? "day" : "month";
        $well_number = $model->well_number;
        $file = $model->file;
        // $content = "{$well_number}措施前产量计算，向前推算至多{$measures_before_times}，每次间隔{$measures_before_interval}{$measures_before_type}";
        // $this->save_log($well_number,$file,$content);
        //措施前产量
        $end_date = $model->start_date; //措施前产量是向前推算时间，开工时间为结束时间
        $base_end_date = null; //措施前基准日期
        for ($i = 0; $i < $measures_before_times; $i++) {
            $start_date = $this->calculateDate($end_date, 'backward', $measures_before_type, $measures_before_interval);
            $time_array = [$start_date, $end_date];
            try {
                $cyl_model = $model->cyl()->where(function ($query) use ($time_array) {
                    $query->where("RQ BETWEEN TO_DATE('{$time_array[0]} 00:00:00', 'YYYY-MM-DD HH24:MI:SS') AND TO_DATE('$time_array[1] 00:00:00', 'YYYY-MM-DD HH24:MI:SS')");
                })->order('RQ', 'desc')->find();
                if (!empty($cyl_model)) {
                    $base_end_date = $cyl_model->RQ;
                    $content = "{$well_number}在{$time_array[0]}至$time_array[1]查询到{$base_end_date}的产液量>0";
                    $this->save_log($well_number, $file, $content);
                    break;
                } else {
                    $content = "{$well_number}在{$time_array[0]}至$time_array[1]未查询到产液量>0的记录";
                    $this->save_log($well_number, $file, $content);
                }
                $end_date = $start_date;
            } catch (DbException $e) {
                // 处理其他数据库异常（如SQL错误、连接失败等）
                Log::info("数据库错误【" . $e->getMessage() . "】");
            }
        }
        if (!empty($base_end_date)) {
            $base_start_date = $this->calculateDate($base_end_date, 'backward', $measures_before_type, $measures_before_interval);
            $time_array = [$base_start_date, $base_end_date];
            try {
                //查询日产液量>0的记录
                $cyl_model_array = $model->cyl()->where(function ($query) use ($time_array) {
                    $query->where("RQ BETWEEN TO_DATE('{$time_array[0]} 00:00:00', 'YYYY-MM-DD HH24:MI:SS') AND TO_DATE('$time_array[1] 00:00:00', 'YYYY-MM-DD HH24:MI:SS')");
                })->order('RQ', 'asc')->select();
                foreach ($cyl_model_array as $clModel) {
                    $clModel->RCL = $clModel->Rcl;
                    $clModel->file = $model->file;
                }
                //日产液量入库
                $save_model = new BenefitRcl();
                $this->save_data($cyl_model_array->toArray(), $save_model);
                //统计符合条件的日产量的平均值
                $measures_before_cl_query = BenefitRcl::where(array('JH' => $model->well_number, 'file' => $model->file))->where('RCL', '>', intval(benefitConfig('measures_before_yl')))->whereBetweenTime('RQ', "{$time_array[0]} 00:00:00", "{$time_array[1]} 00:00:00");
                $before_cl = $measures_before_cl_query->avg('RCL');
                Log::info("{$well_number}:{$before_cl}");
                $content = "{$well_number}措施前产量：统计{$time_array[0]}至$time_array[1]的平均产量";
                $this->save_log($well_number, $file, $content);
                return formatNumber($before_cl);
            } catch (DbException $e) {
                // 处理其他数据库异常（如SQL错误、连接失败等）
                Log::info("数据库错误【" . $e->getMessage() . "】");
                return -1;
            }
        } else {
            return 0;
        }
    }

    //措施后产量
    public function measures_after_cl($model)
    {
        $measures_after_interval  = benefitConfig('measures_after_interval');
        $measures_after_type  = intval(benefitConfig('measures_after_type')) == 0 ? "day" : "month";
        $measures_after_hs = benefitConfig('measures_after_hs');
        $well_number = $model->well_number;
        $file = $model->file;
        /*
        1.根据以下条件，查找一条记录
        日期范围：[完工日期,完工日期向后推n天/n月] & HS<配置值 & RQ(上报产量的时间)倒序排列
        
        2.如果找到记录了：以这条记录的上报日期为基准向后统计n天/n月的平均产量作为措施后产量；如果没找到记录，措施后产量为0；
        */
        $start_date = $model->end_date;
        $end_date = $this->calculateDate($start_date, 'forward', $measures_after_type, $measures_after_interval);
        //确定日期范围
        $time_array = [$start_date, $end_date];
        $query_str = "TO_NUMBER(HS) < {$measures_after_hs}";
        $cyl_model = null;
        try {
            $cyl_model = $model->cyl()->whereRaw($query_str)->where(function ($query) use ($time_array) {
                $query->where("RQ BETWEEN TO_DATE('{$time_array[0]} 00:00:00', 'YYYY-MM-DD HH24:MI:SS') AND TO_DATE('$time_array[1] 00:00:00', 'YYYY-MM-DD HH24:MI:SS')");
            })->order('RQ', 'asc')->find();
        } catch (DbException $e) {
            // 处理其他数据库异常（如SQL错误、连接失败等）
            Log::info("数据库错误【" . $e->getMessage() . "】");
        }
        if (!empty($cyl_model)) {
            //找到记录了，这条记录的上报时间为基准，向后推算n天/n月
            $base_start_date = $cyl_model->RQ;
            $content = "{$well_number}在{$time_array[0]}至$time_array[1]查询到{$base_start_date}的含水<{$measures_after_hs}";
            $this->save_log($well_number, $file, $content);
            $model->measures_after_date = $base_start_date;
            $base_end_date = $this->calculateDate($base_start_date, 'forward', $measures_after_type, $measures_after_interval);
            $time_array = [$base_start_date, $base_end_date];
            try {
                //查询日产液量记录
                $cyl_model_array = $model->cyl()->where(function ($query) use ($time_array) {
                    $query->where("RQ BETWEEN TO_DATE('{$time_array[0]} 00:00:00', 'YYYY-MM-DD HH24:MI:SS') AND TO_DATE('$time_array[1] 00:00:00', 'YYYY-MM-DD HH24:MI:SS')");
                })->order('RQ', 'asc')->select();
                foreach ($cyl_model_array as $clModel) {
                    $clModel->RCL = $clModel->Rcl;
                    $clModel->file = $model->file;
                }

                //日产液量入库
                $save_model = new BenefitRcl();
                $this->save_data($cyl_model_array->toArray(), $save_model);
                // //统计符合条件的日产量的平均值
                $measures_after_cl_query = BenefitRcl::where(array('JH' => $model->well_number, 'file' => $model->file))->where('RCL', '>', intval(benefitConfig('measures_before_yl')))->whereBetweenTime('RQ', "{$time_array[0]} 00:00:00", "{$time_array[1]} 00:00:00");
                $after_cl = $measures_after_cl_query->avg('RCL');
                $content = "{$well_number}措施后产量：统计{$time_array[0]}至$time_array[1]的平均产量";
                $this->save_log($well_number, $file, $content);
                return formatNumber($after_cl);
            } catch (DbException $e) {
                // 处理其他数据库异常（如SQL错误、连接失败等）
                Log::info("数据库错误【" . $e->getMessage() . "】");
                return -1;
            }
        } else {
            $content = "{$well_number}在{$time_array[0]}至$time_array[1]未查询到含水<{$measures_after_hs}的记录";
            $this->save_log($well_number, $file, $content);
            return 0;
        }
    }

    //查询费用
    public function query_cost($file)
    {
        $well_number_array = BenefitWellNumber::where(array('file' => $file))->select();
        try {
            foreach ($well_number_array as $model) {
                $well_number = $model->well_number;
                $model_file = $model->file;

                //查询满足条件的材料费
                $start = $model->start_date . ' 00:00:00';
                $end = $model->end_date . ' 00:00:00';
                $clf_query = $model->clf()->whereRaw(
                    "TO_DATE(F_FLSJ, 'YYYY-MM-DD HH24:MI:SS') BETWEEN TO_DATE(:start, 'YYYY-MM-DD HH24:MI:SS') AND TO_DATE(:end, 'YYYY-MM-DD HH24:MI:SS')",
                    ['start' => $start, 'end' => $end]
                );
                $clf_model_array = $clf_query->select();
                foreach ($clf_model_array as $clf_model) {
                    $clf_model->FILE = $model_file;
                }
                //入库材料费
                $save_model = new BenefitZcf();
                $this->save_data($clf_model_array->toArray(), $save_model);

                //查询满足条件的劳务费
                $lwf_query = $model->lwf()->where(array('F_KGRQ' => str_replace('-', '', $model->start_date), 'F_WGRQ' => str_replace('-', '', $model->end_date)));
                $dmbtr = $lwf_query->sum('F_DMBTR');
                $lwf_data_array = array(
                    'F_GCMC' => $well_number,
                    'F_KGRQ' => $model->start_date,
                    'F_WGRQ' => $model->end_date,
                    'F_DMBTR' => $dmbtr,
                    'FILE' => $model_file,
                    'TYPE' => 0
                );
                //入库普通劳务费
                $save_model = new BenefitLwf();
                $save_model->save($lwf_data_array);

                //自营修复劳务费
                $save_model = new BenefitLwf();
                $lwf_data_array['TYPE'] = 1;
                $lwf_data_array['F_DMBTR'] = $model->zylwf()->where('file', $model->file)->sum('F_JE');
                $save_model->save($lwf_data_array);

                //外部修复劳务费
                $save_model = new BenefitLwf();
                $lwf_data_array['TYPE'] = 2;
                $lwf_data_array['F_DMBTR'] = $model->wblwf()->where('file', $model->file)->sum('F_JE');
                $save_model->save($lwf_data_array);
            }
        } catch (DbException $e) {
            // 处理其他数据库异常（如SQL错误、连接失败等）
            Log::info("数据库错误【" . $e->getMessage() . "】");
            return false;
        }
        return true;
    }


    //上传文件
    public function upload_file(Request $request)
    {
        $post = $request->post();
        $files = $request->file();
        $uploadConfig = sysConfig('upload');
        $upload_type = $uploadConfig['upload_type'];
        $range = $post['start'] . '/' . $post['end'];
        $uploadConfig['date_range'] = $range;
        try {
            $upload = UploadService::instance()->setConfig($uploadConfig)->$upload_type($files['file'], 'upload'); //上传
            return $upload;
        } catch (\Exception $e) {
            Log::error('文件上传失败:' . $e->getMessage());
            return array('code' => 0);
        }
    }

    /**
     * 读取Excel文件数据
     * @param string $filePath Excel文件路径
     * @return array|false 成功返回数据数组，失败返回false
     */
    function readExcelData($filePath, $fileName, $range)
    {
        Log::info("读取Excel数据。{$filePath}");
        try {
            // 根据文件后缀自动选择读取器
            $reader = IOFactory::createReaderForFile($filePath);

            // 设置只读模式（提高性能）
            $reader->setReadDataOnly(true);

            // 加载Excel文件
            $spreadsheet = $reader->load($filePath);

            // 获取活动工作表（默认第一个工作表）
            $worksheet = $spreadsheet->getActiveSheet();

            // 获取最大行数和列数
            $highestRow = $worksheet->getHighestRow();
            //$highestRow = 10;
            $highestColumn = $worksheet->getHighestColumn();
            //$highestColumnIndex = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn);
            $saveColumnArray = config('upload.save_column');
            $filterArray = config('upload.filter');
            $filterkeys = array_keys($filterArray);
            $excelMap = config('upload.excel_map');
            $startRow = config('upload.start_row') ?? 1;
            $dateColumn = config('upload.date_column');
            $data = [];
            // 循环读取数据（从第1行开始）
            for ($row = $startRow; $row <= $highestRow; $row++) {
                $rowData = [];
                $fileter_res = [];
                for ($i = 0; $i < count($filterkeys); $i++) {
                    $filter_key = $filterkeys[$i];
                    $filter_content = $filterArray[$filter_key];
                    $cell = $worksheet->getCell($filter_key . strval($row));
                    $value = $cell->getFormattedValue();
                    if (in_array($value, $filter_content)) {
                        array_push($fileter_res, 'true');
                    } else {
                        array_push($fileter_res, 'false');
                    }
                }
                if (in_array('false', $fileter_res)) {
                    continue;
                }
                $rowData = [];
                $res = empty($range);
                $filter = !empty($range);
                foreach ($saveColumnArray as $col) {
                    $cell = $worksheet->getCell($col . strval($row));
                    if (in_array($col, $dateColumn)) {
                        $cell->getStyle()->getNumberFormat()->setFormatCode(
                            NumberFormat::FORMAT_DATE_YYYYMMDD
                        );
                    }
                    $isDate = Date::isDateTime($cell);
                    $value = null;
                    if ($isDate) {
                        $dateTime = Date::excelToDateTimeObject($cell->getValue());
                        $value = $dateTime->format('Y-m-d');
                        if ($filter) {
                            $rangeArray = explode('/', $range);
                            $startDate = $rangeArray[0];
                            $endDate = $rangeArray[1];
                            if ($col == 'K') {
                                // 目标日期
                                $targetDate = $value;
                                // 日期范围
                                $targetTimestamp = strtotime($targetDate);
                                $startTimestamp = strtotime($startDate);
                                $endTimestamp = strtotime($endDate);
                                if ($targetTimestamp >= $startTimestamp && $targetTimestamp <= $endTimestamp) {
                                    $res = true;
                                }
                            }
                        }
                    } else {
                        $value = $cell->getFormattedValue();
                    }

                    if (isset($excelMap[$col])) {
                        $rowData[$excelMap[$col]] = $this->formatNumeric($value);
                    }
                    $rowData['file'] = $fileName;
                    $rowData['user'] = session('admin.id');
                }
                if ($res) {
                    $data[] = $rowData;
                }
            }

            return $data;
        } catch (Exception $e) {
            Log::error("读取Excel错误{$e->getMessage()}");
            return [];
        }
    }

    ///格式化数字，读取的日期列获取到的是数字，还原成日期
    private function formatNumeric($cellValue)
    {
        if (is_numeric($cellValue)) {
            // 检查是否可能是日期（Excel日期范围大致在25569到44927之间）
            if ($cellValue > 25569 && $cellValue < 44927) {
                // 转换为DateTime对象
                $dateTime = Date::excelToDateTimeObject($cellValue);
                $formattedDate = $dateTime->format('Y-m-d'); // 自定义格式
            } else {
                // 不是日期，直接使用原值
                $formattedDate = $cellValue;
            }
            return $formattedDate;
        } else {
            return $cellValue;
        }
    }

    // 删除文件
    private function deletefile($name)
    {
        $model = SystemUploadfile::where('new_name', $name)->find();
        if (!empty($model)) {
            $where['file'] = $name;
            BenefitLog::where($where)->delete();
            BenefitLwf::where($where)->delete();
            BenefitRcl::where($where)->delete();
            BenefitWellNumber::where($where)->delete();
            BenefitZcf::where($where)->delete();
            $path = $model->url;
            try {
                $filePath = app()->getRootPath() . 'public/' . $path;
                // // 检查文件是否存在
                if (file_exists($filePath)) {
                    unlink($filePath);
                }
            } catch (ValidateException $e) {
                Log::error($e->getMessage());
            }
            $model->delete();
        }
    }

    ///数据入库
    private function save_data($data, $model)
    {
        $batchSize = 500; // 每批插入数量
        $total = count($data);
        for ($i = 0; $i < $total; $i += $batchSize) {
            // 截取批次数据
            $batchData = array_slice($data, $i, $batchSize);
            $model->insertAll($batchData);
        }
    }

    ///清空数据
    public function empty()
    {
        $table = array('b_benefit_well_number', 'b_benefit_lwf', 'b_benefit_zcf');
        for ($i = 0; $i < count($table); $i++) {
            $command = "TRUNCATE " . $table[$i];
            Db::execute($command);
            $command = "ALTER TABLE " . $table[$i] . ' AUTO_INCREMENT = 1';
            Db::execute($command);
        }
        $this->success('已清空所有数据');
    }

    /**
     * 计算日期
     * @param string $start 开始日期
     * @param int $type 类型0-措施前 1-措施后
     * @return string 结束日期
     */
    public function calculate_date($start, $type)
    {
        if ($type == 0) {
        }
    }

    /**
     * 灵活计算日期
     * @param string $baseDate 基准日期（默认当前日期，格式：Y-m-d）
     * @param string $direction 方向：forward(向后)、backward(向前)
     * @param string $type 类型：day(天)、month(月)
     * @param int $value 数量（正整数）
     * @return string 计算后的日期（格式：Y-m-d）
     * @throws InvalidArgumentException 当参数无效时抛出异常
     */
    function calculateDate($baseDate = '', $direction = 'forward', $type = 'day', $value = 1)
    {
        // 验证基准日期，默认使用当前日期
        if (empty($baseDate)) {
            $baseDate = date('Y-m-d');
        } else {
            $dateObj = DateTime::createFromFormat('Y-m-d', $baseDate);
            if (!$dateObj) {
                return '';
                Log::error("基准日期格式无效，请使用 Y-m-d 格式");
            }
        }

        // 验证方向参数
        if (!in_array($direction, ['forward', 'backward'])) {
            return '';
            Log::error("方向参数无效，必须是 'forward' 或 'backward'");
        }

        // 验证类型参数
        if (!in_array($type, ['day', 'month'])) {
            return '';
            Log::error("类型参数无效，必须是 'day' 或 'month'");
        }

        // 验证数量参数
        if (!is_int($value) || $value <= 0) {
            return '';
            Log::error("数量必须是正整数");
        }

        // 创建日期对象
        $date = new DateTime($baseDate);

        // 计算符号（向前为正，向后为负）
        $sign = $direction === 'forward' ? '+' : '-';

        // 构建修改字符串（如 "+3 days"、"-2 months"）
        $modifyString = "{$sign}{$value} {$type}s";
        // 执行日期修改
        $date->modify($modifyString);

        // 返回格式化后的日期
        return $date->format('Y-m-d');
    }

    ///计算两个日期的差
    public function dateinterval($start, $end)
    {
        $date1 = new DateTime($start);
        $date2 = new DateTime($end);
        $interval = $date1->diff($date2);
        return $interval->days;
    }

    public function save_log($well_number, $file, $content)
    {
        $data = array('user' => session('admin.id'), 'well_number' => $well_number, 'file' => $file, 'content' => $content);
        $log_model = new BenefitLog();
        $log_model->save($data);
    }
}
